<template>
  <div class="container" v-loading="shareLoading">
    <div class="card-box">
      <div class="title">分享邀请他人填写</div>
      <div class="share-common">
        <div class="common-left">
          <qrcodeImg :shareInfo="shareInfo" ref="qrcodeImgRef"></qrcodeImg>
        </div>
        <div class="common-right">
          <div class="right-title">分享链接</div>
          <div class="form-links">
            <el-input class="link-text" v-model="shareInfo.link" size="large" disabled></el-input>
            <el-button class="link-copy" type="primary" size="large" @click="copyLink">复制链接</el-button>
            <el-tooltip effect="dark" content="直接打开" placement="top">
              <a class="link-open" :href="shareInfo.link" target="_blank">
                <i class="iconfont">&#xe676;</i>
              </a>
            </el-tooltip>
          </div>
          <div class="form-customs">
            <div class="link-custom" @click="downloadQrcodeImg">
              <i class="iconfont">&#xe646;</i>
              下载二维码
            </div>
            <el-popover placement="right-end" trigger="hover" :width="324">
              <template #reference>
                <div class="link-custom" @click="downloadQrcodePoster">
                  <i class="iconfont">&#xe6ab;</i>
                  生成二维码海报
                </div>
              </template>
              <qrcodePoster ref="poster" :formLink="shareInfo.link" :formId="formId"></qrcodePoster>
            </el-popover>
          </div>
          <div class="form-permission">
            <span class="permission-cur" @click="goSetting">
              {{ currentCooperate }}
              <el-icon>
                <ArrowRight />
              </el-icon>
            </span>
          </div>
          <div class="form-notice"></div>
        </div>
      </div>
    </div>
    <div class="card-box">
      <div class="title">自定义来源</div>
      <div class="source-custom">
        <div class="custom-left">支持预设多个来源名称。用于邀请填写时，标记和区分不同来源填写内容</div>
        <div class="custom-right" @click="sourceCustomShow = true">
          {{ sourceCustomText }}
          <span>
            <el-icon>
              <ArrowRight />
            </el-icon>
          </span>
        </div>
      </div>
    </div>
    <sourceCustom v-model:sourceCustomShow="sourceCustomShow" v-model:sourceCustomNum="sourceCustomNum" :formId="formId" :formLabel="shareInfo.title"></sourceCustom>
  </div>
</template>
<script setup>
import { ref, computed, onBeforeMount } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'
import { useStore } from 'vuex'
import { useRouter, useRoute } from 'vue-router'
import sourceCustom from './sourceCustom.vue'
import qrcodePoster from './qrcodePoster.vue'
import { getShareInfo, getCurFormInfo } from '@/api/formDesign'
import qrcodeImg from './qrcodeImg.vue'
import { encrypt, decrypt, hasPermission } from '@ruifox-cms/utils'

const props = defineProps({
  curShareFormId: {
    type: String
  }
})
const router = useRouter()
const route = useRoute()
const store = useStore()
const publishSettingStore = computed(() => store.getters.formDesignInfo.publishSetting)
const formId = ref('')
//表单分享基本信息
const shareLoading = ref(false)
const shareInfo = ref({})
const sourceCustomNum = ref(0)
const getBaseInfo = async () => {
  shareLoading.value = true
  try {
    let res = await getShareInfo({ formId: decrypt(route.query.formId || props.curShareFormId) })
    if (res.code === 20000) {
      shareInfo.value = res.data
      if (process.env.NODE_ENV === 'development') {
        shareInfo.value.link = location.protocol + '//' + location.hostname + ':8080/?formKey=' + res.data.link
      } else {
        shareInfo.value.link = location.origin + '/formFront?formKey=' + res.data.link
      }
      sourceCustomNum.value = res.data.customSourceNum
    }
    shareLoading.value = false
  } catch {
    shareLoading.value = false
  }
}
getBaseInfo()
//自定义来源
const sourceCustomShow = ref(false)
const sourceCustomText = computed(() => {
  if (sourceCustomNum.value) {
    return `已设置${sourceCustomNum.value}个来源`
  }
  return '未设置'
})
//复制链接
const copyLink = () => {
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard
      .writeText(shareInfo.value.link)
      .then(() => {
        ElMessage({
          message: '复制成功',
          type: 'success'
        })
      })
      .catch(error => {
        ElMessage({
          message: '复制失败，请再次尝试',
          type: 'error'
        })
        console.log('复制链接到剪贴板时出错:', error)
      })
  } else {
    // 创建text area
    let textArea = document.createElement('textarea')
    textArea.value = shareInfo.value.link
    // 使text area不在viewport，同时设置不可见
    textArea.style.position = 'absolute'
    textArea.style.opacity = 0
    textArea.style.left = '-999999px'
    textArea.style.top = '-999999px'
    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()
    return new Promise((res, rej) => {
      if (document.execCommand('copy')) {
        res()
        ElMessage({
          message: '复制成功',
          type: 'success'
        })
      } else {
        rej()
        ElMessage({
          message: '复制失败，请再次尝试',
          type: 'error'
        })
      }
      textArea.remove()
    })
  }
}
//下载二维码图片
const qrcodeImgRef = ref(null)
const downloadQrcodeImg = () => {
  qrcodeImgRef.value.downloadQrcodeImg()
}
//下载二维码海报
const poster = ref(null)
const downloadQrcodePoster = () => {
  poster.value.downloadQrcodePoster()
}
//谁可以填写
const cooperateOptions = ref([
  { label: 0, name: '仅自己可见和管理' },
  { label: 1, name: '所有人可见和管理' },
  { label: 2, name: '指定人员可见和管理' }
])
const currentCooperate = computed(() => cooperateOptions.value[publishSettingStore.value.useLimitCooperate].name)
const goSetting = () => {
  if (hasPermission(['form:manage:design:edit'])) {
    router.push({ path: '/form/manage/design', query: { from: 'share', formId: encrypt(formId.value), id: route.query.id || encrypt(publishSettingStore.value.typeId) } })
  } else {
    ElMessage.error('无权限')
  }
}
onBeforeMount(async () => {
  formId.value = decrypt(route.query.formId || props.curShareFormId)
  //如果是从列表进入该组件，由于其子组件值获取都来源于store，需请求表单信息设置一下store
  if (props.curShareFormId) {
    let res = await getCurFormInfo({ formId: formId.value })
    store.commit('formDesignInfo/SET_FORMINFO', res.data)
  }
})
</script>
<style lang="scss" scoped>
.container {
  width: 100%;
  height: calc(100vh - 64px);
  overflow: auto;
  padding-top: 10px;
  background-color: var(--el-color-primary-light-9);

  .card-box {
    width: 960px;
    margin: 0 auto;
    margin-bottom: 20px;
    border-radius: 6px;
    box-shadow: 0 0 4px rgba(0, 0, 0, 0.05);
    padding: 20px 40px 30px;
    box-sizing: border-box;
    background-color: #ffffff;
    font-size: 16px;

    .title {
      margin-bottom: 20px;
      font-size: 20px;
      font-weight: 600;
      color: #333333;
    }
  }

  .share-common {
    display: flex;
    flex-wrap: nowrap;
    font-size: 14px;
    color: #444444;

    // .common-left {
    //     display: flex;
    //     flex-direction: column;
    //     justify-content: center;
    //     align-items: center;
    //     margin-right: 20px;
    //     padding: 20px;
    //     width: 170px;
    //     border: 1px solid #e4e4e4;
    //     border-radius: 8px;

    //     .form-title {
    //         margin-bottom: 10px;
    //     }

    //     .form-qrcode {
    //         margin-bottom: 10px;
    //         width: 120px;
    //         height: 120px;

    //         img {
    //             width: 100%;
    //             height: 100%;
    //             background: #797979;
    //         }
    //     }

    //     .form-tip {
    //         font-size: 12px;
    //         color: #AAAAAA;
    //     }
    // }
    .common-left {
      margin-right: 20px;
    }

    .common-right {
      flex: 1;

      .right-title {
        margin-bottom: 10px;
      }

      .form-links {
        display: flex;
        flex-wrap: nowrap;
        margin-bottom: 10px;

        .link-text {
          margin-right: 10px;
          width: 50%;
        }

        .link-copy {
          margin-right: 10px;
        }

        .link-open {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 38px;
          height: 38px;
          border: 1px solid #e4e4e4;
          border-radius: 4px;

          i {
            font-size: 16px;
          }
        }

        .link-open:hover {
          background: #f0f1f1;
        }
      }

      .form-customs {
        display: flex;
        flex-wrap: nowrap;
        margin-bottom: 20px;

        .link-custom {
          margin-right: 10px;
          padding: 10px 20px;
          border: 1px solid #e4e4e4;
          border-radius: 4px;
          cursor: pointer;
        }

        .link-custom:hover {
          background: #f0f1f1;
        }
      }

      .form-permission {
        margin-bottom: 20px;

        .permission-cur {
          display: flex;
          align-items: center;
          cursor: pointer;

          i {
            margin-left: 10px;
          }
        }
      }
    }
  }

  .source-custom {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    color: #444444;

    .custom-right {
      display: flex;
      align-items: center;
      cursor: pointer;
    }
  }
}
</style>
